package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserSerivce;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yu yang
 * @date 2022/9/29 -22:17
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserSerivce userSerivce;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user){
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info(code);
//            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);
//            session.setAttribute(phone,code);
            //将验证码保存到redis缓存中
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        }
        return R.success("验证码发送成功");
    }
    @PostMapping("/login")
    public R<User> login(HttpSession session,@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        String code = map.get("code");

//        String codeConfirm = (String) session.getAttribute(phone);
        //从缓存中获得验证码
        String codeConfirm = (String) redisTemplate.opsForValue().get(phone);

        if (codeConfirm!=null &&codeConfirm.equals(code)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userSerivce.getOne(userLambdaQueryWrapper);
            if (user ==null){
                user = new User();
                user.setPhone(phone);
                userSerivce.save(user);
            }
            session.setAttribute("user",user);
            //登陆成功后移除验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误");
    }
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("成功退出账号");
    }
}
